﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Web;
using Service.Core;
using Service.Core.Interface;
using Service.Core.Result;
using Web.BML.AnalysisData;
using Web.BML.CoreData;
using Web.Models.AnalysisData;
using Web.Models.CoreData;
using Web.ViewModel.CoreData;
using Tools;
using System.IO;
using System.Xml;
using System.IO.Packaging;

namespace Web.Service
{
    public  class ConfigsService : BaseService
    {
        /// <summary>
        /// XML保存的文件路径名
        /// </summary>
        public const string XMLFILEPATH = "/Upload/Configs/";
        /// <summary>
        /// 默认配置文件
        /// </summary>
        public const string DEFAULT = "DEFAULT.xml";
        /// <summary>
        /// 默认报文配置文件
        /// </summary>
        public const string REPORT = "REPORT.xml";

        private ConfigsOp configsOp = ConfigsOp.GetInstance();

        private static ConfigsService instance;

        private ConfigsService()
        {

        }

        public static ConfigsService GetInstance()
        {
            if (instance == null)
            {
                instance = new ConfigsService();
            }
            return instance;
        }

        /// <summary>
        /// 查询用户的配置列表
        /// </summary>
        /// <param name="id">Company的id</param>
        /// <returns></returns>
        public List<Configs> QueryConfigs(String companyId)
        {
            List<Configs> configs = configsOp.QueryByCompanyId(companyId);
            return configs;
        } 

        /// <summary>
        /// 查询所有的配置列表
        /// </summary>
        /// <returns></returns>
        public List<Configs> QueryAll()
        {
            List<Configs> configs = configsOp.QueryAll();
            return configs;
        }
        

        /// <summary>
        /// 读取配置文件
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <returns></returns>
        public IServiceResult ReadConfig(String filename)
        {
            if(!File.Exists(filename))
            {
                return Result(ResultType.TargetIsNotFound,"文件不存在，请重新创建");
            }
            String content = FileHelper.Text.ReadTxt(filename);
            return Result(ResultType.Success,content,null);
        }

        /// <summary>
        /// 获取用户配置信息
        /// </summary>
        /// <param name="token">用户许可号</param>
        /// <returns></returns>
        public IServiceResult GetUserConfig(String token)
        {
            User user = UserOp.GetInstance().QueryUser(token);
            if(user==null)
            {
                return Result(ResultType.ParamIsError, "许可号错误");
            }
            string str = "";
            if(string.IsNullOrEmpty(user.Configs))
            {
                str=FileHelper.Text.ReadTxt(HttpContext.Current.Server.MapPath("~") + Path.Combine(XMLFILEPATH, user.Company, DEFAULT));
            }else
            {
                str = FileHelper.Text.ReadTxt(HttpContext.Current.Server.MapPath("~") + configsOp.Query(user.Configs).FilePath);
            }
            return Result(ResultType.Success, str, "操作成功");
        }

        /// <summary>
        /// 创建配置文件
        /// </summary>
        /// <param name="name">配置项名称</param>
        /// <param name="id">Company的id</param>
        /// <returns></returns>
        public IServiceResult AddConfig(String name,String id)
        {
            string path = Path.Combine(XMLFILEPATH, id);
            Configs configs = new Configs() {
                CompanyId=id,
                ConfigName=name,
                Id=Guid.NewGuid().ToString(),
                Description=string.Empty
            };
            configs.FilePath = Path.Combine(path, configs.Id + ".xml");
            if (!configsOp.CreateConfigs(configs))
            {
                return Result(ResultType.Fail, "请尝试刷新页面重新操作");
            }
            string cur = HttpContext.Current.Server.MapPath("~");
            if(!Directory.Exists(cur+path))
            {
                Directory.CreateDirectory(cur+path);
            }
            File.Copy(cur+Path.Combine(path, DEFAULT), cur+Path.Combine(path, configs.Id+".xml")); 
            return Result(ResultType.Success, configs);
        }

        /// <summary>
        /// 删除配置项
        /// </summary>
        /// <param name="id">配置项id</param>
        /// <returns></returns>
        public IServiceResult DeleteConfigs(String id)
        {
            List<User> userList = UserOp.GetInstance().QueryUserConfig(id);
            if(userList.Count>0)
            {
                string msg = String.Join(",", userList.Select(m => m.UserName).ToArray());
                return Result(ResultType.Fail,msg+"，请先解除以上用户的设置");
            }
            Configs configs = configsOp.Query(id);
            if(configs==null)
            {
                return Result(ResultType.Success);
            }

            File.Delete(HttpContext.Current.Server.MapPath("~")+ configs.FilePath);
            if(configsOp.DeleteConfigs(configs))
            {
                return Result(ResultType.Success);
            }
            else
            {
                return Result(ResultType.Fail, "请尝试刷新页面重新操作");
            }
        }

        /// <summary>
        /// 创建报文配置文件
        /// </summary>
        /// <param name="companyId">用户id</param>
        public void CreateReportConfig(string companyId)
        {
            string path = Path.Combine(XMLFILEPATH, companyId);
            string cur = HttpContext.Current.Server.MapPath("~");
            Configs configs = new Configs()
            {
                CompanyId = companyId,
                ConfigName = "Report",
                Id = Guid.NewGuid().ToString(),
                Description = "报文软件程序配置文件",
                FilePath = Path.Combine(path, REPORT)
            };
            configsOp.CreateConfigs(configs);
            if (!Directory.Exists(cur + path))
            {
                Directory.CreateDirectory(cur + path);
            }
            File.Copy(cur + Path.Combine(XMLFILEPATH, REPORT), cur + Path.Combine(path, REPORT));
        }

        /// <summary>
        /// 创建默认配置文件
        /// </summary>
        /// <param name="companyId">用户id</param>
        public void CreateDefaultConfig(string companyId)
        {
            string path = Path.Combine(XMLFILEPATH, companyId);
            string cur = HttpContext.Current.Server.MapPath("~");
            Configs configs = new Configs()
            {
                CompanyId = companyId,
                ConfigName = "Default",
                Id = Guid.NewGuid().ToString(),
                Description = "报文软件程序配置文件",
                FilePath = Path.Combine(path, DEFAULT)
            };
            configsOp.CreateConfigs(configs);
            if (!Directory.Exists(cur + path))
            {
                Directory.CreateDirectory(cur + path);
            }
        }

        /// <summary>
        /// 更新配置项
        /// </summary>
        /// <param name="configs">配置项值</param>
        /// <param name="content">配置内容</param>
        /// <returns></returns>
        public IServiceResult ModifConfigs(Configs configs,String content)
        {
            Configs model = configsOp.Query(configs.Id);
            if (model == null)
            {
                return Result(ResultType.TargetIsNotFound);
            }
            model.ConfigName = configs.ConfigName;
            model.Description = configs.Description;
            FileHelper.Text.WriteTxt(HttpContext.Current.Server.MapPath("~") + model.FilePath, content);
            if (configsOp.ModifConfigs(model))
            {
                return Result(ResultType.Success);
            }
            else
            {
                return Result(ResultType.Fail, "请尝试刷新页面重新操作");
            }
        }

        /// <summary>
        /// 下载配置文件
        /// </summary>
        /// <param name="id">配置文件id</param>
        /// <param name="savePath">文件保存路径地址</param>
        /// <returns></returns>
        public IServiceResult DownLoadConfig(String id)
        {
            if(ParamsIsNull(id))
            {
                return Result(ResultType.ParamIsNull);
            }
            Configs configs = configsOp.Query(id);
            string targetPath = HttpContext.Current.Server.MapPath("~") + configs.FilePath;
            string dstPath = Path.Combine(Path.GetDirectoryName(targetPath)+ "\\Configs.zip");
            FileHelper.ZipFile(targetPath, dstPath , "Config.xml");
            return Result(ResultType.Success,dstPath.Replace(HttpContext.Current.Server.MapPath("~"),"/"),null);
        }


    }
}